package com.haynes.meetxiaohai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haynes.meetxiaohai.common.CustomException;
import com.haynes.meetxiaohai.entity.Category;
import com.haynes.meetxiaohai.entity.Dish;
import com.haynes.meetxiaohai.entity.Setmeal;
import com.haynes.meetxiaohai.mapper.CategoryMapper;
import com.haynes.meetxiaohai.service.CategoryService;
import com.haynes.meetxiaohai.service.DishService;
import com.haynes.meetxiaohai.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author Haynes
 * @Date 2023/3/20 10:07
 * @PackageName:com.haynes.reggie.service.impl
 * @ClassName: CategoryServiceImpl
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据ID删除分类
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
//        创建条件查询对象，根据分类ID查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);

//        查询当前分类下是否有菜品
        int dishesCount = dishService.count(dishLambdaQueryWrapper);
        if (dishesCount > 0) {
//            如果大于0，说明分类下有菜品，需要抛出业务异常
            throw new CustomException("当前分类下有菜品无法删除！");
        }

        LambdaQueryWrapper<Setmeal> SetmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        SetmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);

//        查询当前分类下是否有套餐
        int SetmealCount = dishService.count(dishLambdaQueryWrapper);
        if (SetmealCount > 0) {
//            如果大于0，说明分类下有套餐，需要抛出业务异常
            throw new CustomException("当前分类下有套餐无法删除！");
        }

//        如果上述条件都不满足则直接删除分类
        super.removeById(id);
    }
}
